package com.mall.message;

import com.mall.manager.pojo.TbItem;
import com.mall.manager.pojo.TbItemDesc;
import com.mall.manager.service.ItemService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class ItemMessageConsumer {

    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private ItemService itemService;

    @Value("${htmlPath}")
    private String htmlPath;


    /**
     * 接收item队列消息并根据id利用freemarker模板创建HTML
     */
    @JmsListener(destination = "item-topic")
    public void receive(String itemId) throws IOException, TemplateException {
        log.debug("静态化商品页面id="+itemId);
        long id = Long.parseLong(itemId);
        //查询出商品信息
        TbItem item = itemService.getItemById(id);
        TbItemDesc itemDesc = itemService.getItemDescById(id);
        //创建一个数据集，把商品数据封装
        Map data = new HashMap<>(0);
        data.put("item", item);
        data.put("itemDesc", itemDesc);
        //加载模板对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = null;
            template = configuration.getTemplate("item.ftl");
        //创建一个输出流，指定输出的目录及文件名。
        Writer out = new FileWriter(htmlPath + itemId + ".html");
        //生成静态页面。
            template.process(data, out);
        //关闭流
            out.close();
    }

}
